package com.imax.center.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

/**
 * 文件工具类
 */
public class MyFileUtils {

    /**
     * 通过文件名获取一个uuid+文件扩展名的文件名
     * @param fileName
     * @return
     */
    public static String getUuidFileName(String fileName) {
        return UUID.randomUUID().toString().replace("-", "") + "." + getFileExtension(fileName);
    }

    /**
     * 将网络图片URL转换为MultipartFile
     *
     * @param imageUrl http或https开头的图片URL
     * @return MultipartFile对象
     * @throws IOException 如果发生IO异常
     */
    public static MultipartFile urlToMultipartFile(String imageUrl) throws IOException {
        // 验证URL
        if (imageUrl == null || !(imageUrl.startsWith("http://") || imageUrl.startsWith("https://"))) {
            throw new IllegalArgumentException("图片URL必须以http://或https://开头");
        }
        
        // 创建URL连接
        URL url = new URL(imageUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(10000);
        
        // 获取文件名
        String fileName = getFileNameFromUrl(imageUrl);
        String fileExtension = getFileExtension(fileName);
        if (fileExtension.isEmpty()) {
            // 如果无法从URL获取文件扩展名，根据Content-Type自动获取
            String contentType = connection.getContentType();
            fileExtension = getExtensionFromContentType(contentType);
            fileName = UUID.randomUUID().toString() + "." + fileExtension;
        }
        
        // 读取远程文件内容
        try (InputStream inputStream = connection.getInputStream();
             ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            
            byte[] bytes = outputStream.toByteArray();
            String contentType = connection.getContentType();
            
            // 创建自定义MultipartFile对象
            return new ByteArrayMultipartFile(
                    "file", 
                    fileName,
                    contentType, 
                    bytes
            );
        } finally {
            // 断开连接
            connection.disconnect();
        }
    }
    
    /**
     * 自定义MultipartFile实现类，基于字节数组
     */
    private static class ByteArrayMultipartFile implements MultipartFile {
        private final String name;
        private final String originalFilename;
        private final String contentType;
        private final byte[] content;

        public ByteArrayMultipartFile(String name, String originalFilename, String contentType, byte[] content) {
            this.name = name;
            this.originalFilename = originalFilename;
            this.contentType = contentType;
            this.content = content;
        }

        @Override
        public String getName() {
            return name;
        }

        @Override
        public String getOriginalFilename() {
            return originalFilename;
        }

        @Override
        public String getContentType() {
            return contentType;
        }

        @Override
        public boolean isEmpty() {
            return content == null || content.length == 0;
        }

        @Override
        public long getSize() {
            return content != null ? content.length : 0;
        }

        @Override
        public byte[] getBytes() throws IOException {
            return content;
        }

        @Override
        public InputStream getInputStream() throws IOException {
            return new ByteArrayInputStream(content);
        }

        @Override
        public void transferTo(File dest) throws IOException, IllegalStateException {
            try (FileOutputStream fos = new FileOutputStream(dest)) {
                fos.write(content);
            }
        }
    }
    
    /**
     * 从URL中提取文件名
     */
    private static String getFileNameFromUrl(String url) {
        int slashIndex = url.lastIndexOf('/');
        if (slashIndex != -1 && slashIndex < url.length() - 1) {
            String fileName = url.substring(slashIndex + 1);
            // 移除URL参数
            int questionMarkIndex = fileName.indexOf('?');
            if (questionMarkIndex != -1) {
                fileName = fileName.substring(0, questionMarkIndex);
            }
            return fileName;
        }
        return UUID.randomUUID().toString();
    }
    
    /**
     * 获取文件扩展名
     */
    private static String getFileExtension(String fileName) {
        int dotIndex = fileName.lastIndexOf('.');
        if (dotIndex != -1 && dotIndex < fileName.length() - 1) {
            return fileName.substring(dotIndex + 1).toLowerCase();
        }
        return "";
    }
    
    /**
     * 根据Content-Type获取文件扩展名
     */
    private static String getExtensionFromContentType(String contentType) {
        if (contentType == null) {
            return "jpg"; // 默认扩展名
        }
        
        contentType = contentType.toLowerCase();
        
        if (contentType.contains("image/jpeg") || contentType.contains("image/jpg")) {
            return "jpg";
        } else if (contentType.contains("image/png")) {
            return "png";
        } else if (contentType.contains("image/gif")) {
            return "gif";
        } else if (contentType.contains("image/webp")) {
            return "webp";
        } else if (contentType.contains("image/bmp")) {
            return "bmp";
        } else if (contentType.contains("image/svg+xml")) {
            return "svg";
        } else {
            // 默认为jpg
            return "jpg";
        }
    }
} 